package controllers;

import helpers.EncryptionClass;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import beans.LoginBeanRemote;
import dto.DTOUser;
import dto.RepositoryDTO;

/**
 * 
 * @author Horea
 * 
 */

public class MyLoginController {

	@EJB
	LoginBeanRemote pr;

	@ManagedProperty(value = "#{user}")
	DTOUser dtoObj;

	@ManagedProperty(value = "#{repository}")
	RepositoryDTO repDTO;

	private String popUpLogin;
	private String name;
	private String password;
	private String dbName;
	private String dbPassword;
	private String userFailed;
	private String passwordFailed;
	private String dbType;
	private String address;
	private String addressLogout;
	private String repositoryName;
	private String rDTOString;
	private List<RepositoryDTO> repos;
	private List<String> reposString;

	public MyLoginController() {
		this.name = "";
		this.password = "";
		this.addressLogout = "";
		this.repositoryName = "";

	}

	/**
	 * @return The redirected address after login
	 */
	public String addressRedirect() {

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		DTOUser dtoUser = (DTOUser) session.getAttribute("dTOUser");
		dtoUser.setEmail(dtoObj.getEmail());
		dtoUser.setId(dtoObj.getId());
		dtoUser.setName(dtoObj.getName());
		dtoUser.setPassword(dtoObj.getPassword());
		dtoUser.setTelephone(dtoObj.getTelephone());
		dtoUser.setType(dtoObj.getType());

		// internationalization
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////

		if (dbType.equals("admin")) {
			this.repos = pr.populateRepositoryList(dbName);
			address = "adminPage.xhtml?faces-redirect=true";

		} else if (dbType.equals("user")) {
			System.out.println("popup"+popUpLogin);
			if (popUpLogin == null) {
				address = "selectRepository.xhtml";
			} else {
				address = null;
			}
			this.repos = pr.populateRepositoryList(dbName);
			reposString = new ArrayList<String>();
			reposString.add(messageBundle.getString("selectRepository"));
			for (RepositoryDTO e : this.repos) {
				reposString.add(e.getRepName());
			}
		} else{
			address = "login.xhtml?faces-redirect=true";
			
		}
		return address;

	}

	public String selectRepositoryCancel() {
		FacesContext.getCurrentInstance().getExternalContext()
				.invalidateSession();
		return "login.xhtml?faces-redirect=true";
	}

	/**
	 * 
	 * @return Redirected address after logout
	 */
	public String logout() {

		FacesContext.getCurrentInstance().getExternalContext()
				.invalidateSession();

		return "login.xhtml?faces-redirect=true";

	}

	/**
	 * Description : Validate username using DB
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws ValidatorException
	 */
	public void validateName1(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		// internationalization
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////

		String nameForm = (String) value;
		if (nameForm.length() > 0) {

		dtoObj = pr.findDTOUSer(nameForm);

		if (dtoObj.getName().equalsIgnoreCase(nameForm)) {
			dbName = dtoObj.getName();
			dbPassword = dtoObj.getPassword();
			dbType = dtoObj.getType();

		} else {
			dbName = "Invalid name";
			dbPassword = "Invalid password";
			dbType = "Invalid type";
		}
		
		
		if(dbType.equalsIgnoreCase("invalidated")){
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("userInvalid"));
			message.setDetail(messageBundle.getString("userInvalid"));
			context.addMessage("userForm:nameFailed", message);
			throw new ValidatorException(message);
		}
		else if (!nameForm.equalsIgnoreCase(dbName)) {
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(messageBundle.getString("userInvalid"));
				message.setDetail(messageBundle.getString("userInvalid"));
				context.addMessage("userForm:nameFailed", message);
				throw new ValidatorException(message);
			}
		} else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("userForm:nameFailed", message);
			throw new ValidatorException(message);
		}
	}

	/**
	 * Description: Validate password using DB
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws ValidatorException
	 */

	public void validatePassword1(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String passwordForm = (String) value;

		
		
		// internationalization
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////

		if (passwordForm.length() > 0) {
		
		/**
		 * @author soreas
		 * 
		 *         Encrypting password
		 */
		EncryptionClass encryptor = new EncryptionClass();
		String encrypted = encryptor.encryptPassword(passwordForm);
		String encryptedName = encryptor.encryptPassword(dbName);

		
			if (!dbName.equalsIgnoreCase("Invalid name")) {
				if (!encrypted.equalsIgnoreCase(dbPassword)) {
					FacesMessage message = new FacesMessage();
					message.setSeverity(FacesMessage.SEVERITY_ERROR);
					message.setSummary(messageBundle
							.getString("passwordInvalid"));
					message.setDetail(messageBundle
							.getString("passwordInvalid"));
					context.addMessage("userForm:passwordFailed", message);
					throw new ValidatorException(message);
				} else if (encrypted.equalsIgnoreCase(encryptedName)) {
					popUpLogin = "ceva";
					System.out.println("popupceva");
				}
			}
		} else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("userForm:passwordFailed", message);
			throw new ValidatorException(message);
		}

	}

	public String popUpCancel() {
		popUpLogin = null;
		FacesContext.getCurrentInstance().getExternalContext()
				.invalidateSession();
		return null;
	}

	public void getCurrentResourceChanged(ValueChangeEvent e) {
		String newResource = e.getNewValue().toString();
		setRepositoryName(newResource);

	}

	public String selectRepository() {
		String rn = getRepositoryName();
		int idRep = 0;
		String repoName = getRepositoryName();

		if (repoName.compareTo("") != 0) {
			for (RepositoryDTO e : this.repos) {
				if (e.getRepName().equalsIgnoreCase(rn)) {

					idRep = Integer.parseInt(e.getRepID());

					HttpSession session = (HttpSession) FacesContext
							.getCurrentInstance().getExternalContext()
							.getSession(true);
					RepositoryDTO repositoryDTO = (RepositoryDTO) session
							.getAttribute("repositoryDTO");

					// repositoryDTO.setId(e.getId());
					repositoryDTO.setRepName(e.getRepName());
					repositoryDTO.setSupName(e.getSupName());
					repositoryDTO.setUserID(e.getUserID());
					repositoryDTO.setRepID(e.getRepID());

				}
			}

			if (idRep != 0) {
				String i = "" + idRep;

				String supervisor = pr.findSupervisor(idRep);

				repDTO.setSupName(supervisor);
				repDTO.setRepName(repoName);
				repDTO.setRepID(i);
				repDTO.setId(idRep);

				if (dtoObj.getName().equalsIgnoreCase(supervisor)) {
					address = "supervisorPage.xhtml?faces-redirect=true";
				} else
					address = "userPage.xhtml?faces-redirect=true";

				System.out.println("supervisor este " + repDTO.getSupName()
						+ repDTO.getId());

			}

		} else
			address = "login.xhtml?faces-redirect=true";

		return address;

	}

	public RepositoryDTO getRepDTO() {
		return repDTO;
	}

	public void setRepDTO(RepositoryDTO repDTO) {
		this.repDTO = repDTO;
	}

	public String getRepositoryName() {
		return repositoryName;
	}

	public void setRepositoryName(String repositoryName) {
		this.repositoryName = repositoryName;
	}

	public String getrDTOString() {
		return rDTOString;
	}

	public void setrDTOString(String rDTOString) {
		this.rDTOString = rDTOString;
	}

	public String getAddressLogout() {
		return addressLogout;
	}

	public void setAddressLogout(String addressLogout) {
		this.addressLogout = addressLogout;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<String> getReposString() {
		return reposString;
	}

	public void setReposString(List<String> reposString) {
		this.reposString = reposString;
	}

	public List<RepositoryDTO> getRepos() {
		return repos;
	}

	public void setRepos(List<RepositoryDTO> repos) {
		this.repos = repos;
	}

	public String getUserFailed() {
		return userFailed;
	}

	public void setUserFailed(String userFailed) {
		this.userFailed = userFailed;
	}

	public String getPasswordFailed() {
		return passwordFailed;
	}

	public void setPasswordFailed(String passwordFailed) {
		this.passwordFailed = passwordFailed;
	}

	public DTOUser getDtoObj() {
		return dtoObj;
	}

	public void setDtoObj(DTOUser dtoObj) {
		this.dtoObj = dtoObj;
	}

	public String getDbName() {
		return dbName;
	}

	public String getDbPassword() {
		return dbPassword;
	}

	public String getDbType() {
		return dbType;
	}

	public void setDbType(String dbType) {
		this.dbType = dbType;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPopUpLogin() {
		return popUpLogin;
	}

	public void setPopUpLogin(String popUpLogin) {
		this.popUpLogin = popUpLogin;
	}

}
